package com.example.service.impl;

import com.example.entity.LeaveRequest;
import com.example.service.FlowService;
import org.flowable.engine.HistoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 工作流服务实现类
 */
@Service
public class FlowServiceImpl implements FlowService {
    
    @Autowired
    private RuntimeService runtimeService;
    
    @Autowired
    private TaskService taskService;
    
    @Autowired
    private HistoryService historyService;
    
    @Override
    public String startLeaveProcess(LeaveRequest leaveRequest) {
        // 构建流程变量
        Map<String, Object> variables = new HashMap<>();
        variables.put("requester", leaveRequest.getRequester());
        variables.put("requesterName", leaveRequest.getRequesterName());
        variables.put("leaveType", leaveRequest.getLeaveType());
        variables.put("startDate", leaveRequest.getStartDate());
        variables.put("endDate", leaveRequest.getEndDate());
        variables.put("days", leaveRequest.getDays());
        variables.put("reason", leaveRequest.getReason());
        variables.put("manager", leaveRequest.getManager());
        variables.put("managerName", leaveRequest.getManagerName());
        variables.put("status", "pending");
        
        // 启动流程实例
        org.flowable.engine.runtime.ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("leaveRequestProcess", variables);
        
        // 返回流程实例ID
        return processInstance.getProcessInstanceId();
    }
    
    @Override
    public List<Task> findTasksByAssignee(String assignee) {
        return taskService.createTaskQuery().taskAssignee(assignee).list();
    }
    
    @Override
    public void completeTask(String taskId, Map<String, Object> variables) {
        taskService.complete(taskId, variables);
    }
    
    @Override
    public List<HistoricTaskInstance> getProcessHistory(String processInstanceId) {
        return historyService.createHistoricTaskInstanceQuery()
                .processInstanceId(processInstanceId)
                .orderByHistoricTaskInstanceEndTime().asc()
                .list();
    }
    
    @Override
    public Map<String, Object> getProcessVariables(String executionId) {
        return runtimeService.getVariables(executionId);
    }
}